<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/12/13
 * Time: 10:40
 */

namespace app\api\service;

use app\api\model\CouponCode;
use app\api\model\Follow;
use app\api\model\Label;
use app\api\model\User as UserModel;
use app\api\model\Behavior;
use app\api\model\UserWorkuser;
use app\api\model\WorkUser;
use think\Cache;
use think\Config;

class User
{
    /**
     * 获取用户信息
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getUserInfo($wu_id,$uid){
        $user = UserWorkuser::getUserInfoByUid($wu_id,$uid);
        return $user;
    }

    /**
     * 获取用户列表
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUsetList($wu_id,$type){
        if ($type=='rate'){
            $list = UserWorkuser::getUserList($wu_id);
        }
        if($type=='follow'){
            $list = Follow::getUserbyOrder($wu_id);
            foreach ($list as $value){
                $value->time  = getTimeDifference(time() - $value->time );
            }
        }
        if ($type=='activity'){
            $behavior = new Behavior();
            $list =  $behavior->getUid($wu_id);
            foreach ($list as $value){
                $value->time  = getTimeDifference(time() - $value->add_time );
            }
        }
        return $list;
    }

    /**
     * 检查用户是否授权电话号码
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function checkAuthPhone($w_id,$uid){
        $cache = Cache::connect(Config::get('cache.redis'));
        $cache->handler()->select(15);
        $phone =  $cache->handler()->get('user:auth:phone:'.$uid);
        if (!empty($userInfo)){
            return json_decode($phone);
        }
        $phone = UserWorkuser::checkAuthPhone($w_id,$uid);
        if (!empty($user)){
            $cache->handler()->set('user:auth:phone:'.$uid,json_encode($phone),7200);
        }
        return $phone;
    }


    /**
     *用户成交率数量
     * @param $type
     * @return array
     */
    public function getRateNum($wu_id,$type){
        $num = \app\api\model\UserWorkuser::getRateNum($wu_id,0.00,$type['0']);
        $num2 = \app\api\model\UserWorkuser::getRateNum($wu_id,$type['0'],$type['1']);
        $num3 = \app\api\model\UserWorkuser::getRateNum($wu_id,$type['1'],$type['2']);
        $array = array($num,$num2,$num3);
        return $array;
    }
    /**
     * 更新用户信息
     * @param $data
     * @param $id
     * @return $this
     */
    public function updateUser($data,$wu_id,$user_id){
        //清空用户信息
        if (isset($data['close_status']) && $data['close_status'] == 2){
                $data['closed_time'] = time();
        }
        $user = UserWorkuser::updateUser($data,$wu_id,$user_id);
        return $user;
    }

    /**
     * 添加用户标签
     * @param $data
     * @param $uid
     * @return $this
     */
    public function addLabelByUser($data,$wu_id){
        if ($data['label'] !=  null){
            $result = UserModel::addUserLabel($wu_id,$data);
        }
        if ($data['del'] != null){
            $result = UserModel::deleteUserLabelById($data);
            $result = 'success';
        }
        if ($data['add'] != null){
            $result = UserModel::addUserLabelById($data,$wu_id);
        }
        return $result;
    }

    /**
     * 删除标签
     * @param $id
     * @return int
     */
    public function deleteLabel($id){
        $result = Label::deleteLabel($id);
        return $result;
    }

    /**
     * 更新标签
     * @param $data
     * @param $users
     * @param $id
     * @return $this
     */
    public function updateLabel($data,$users,$id){
        $result = Label::updateLabel($data,$users,$id);
        return $result;
    }

    /**
     * 添加用户标签
     * @param $data
     * @param $users
     * @return $this
     */
    public function addLabel($wu_id,$data,$users){
        $data['wu_id'] = $wu_id;
        $result =  Label::getLabel($wu_id,$data['name']);
        if (empty($result)){
            $result = Label::addLabel($data,$wu_id,$users);
        }
        return $result;
    }


    /**
     * 获取标签列表
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getLabelList($wu_id){
        $result = Label::getLabelList($wu_id);
        return $result;
    }

    /**
     * 获取标签用户
     * @param $id
     * @return \think\model\relation\BelongsToMany
     */
    public function getUserByLabel($id){
        $result = Label::getUuserByLabel($id);
        $result =  $result->toArray();
        foreach ($result['users'] as $key=>$item){
            $result['users'][$key]['user'] = $item;
            unset($result['users'][$key]['avatar_url']);
            unset($result['users'][$key]['id']);
            unset($result['users'][$key]['nickname']);
        }
        return $result;
    }

    /**
     * 获取用户标签
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getLabelBbyUser($uid,$wu_id){
        $result = UserModel::getLabelByUser($wu_id,$uid);
        $result = $result->toArray();
        foreach ($result as $key=>$value){
            $info['id'] = $uid;
            $info['labels'][$key]['id'] =$value['id'];
            $info['labels'][$key]['name'] =$value['name'];
            $info['labels'][$key]['sort']=$value['sort'];
        }
        $phone = UserWorkuser::getUserInfoByUid($wu_id,$uid);//查询用户是否已经授权电话
        $code = CouponCode::getCouponCodeByUserAndWorkUser($uid,$wu_id);
        if (null != $phone->authorize_phone){//特殊标签处理
            $info['labels'][]['name'] = config('label.phone');
        }
        if (!$code->isEmpty()){
            $info['labels'][]['name'] = config('label.coupon');
        }
        return $info;
    }

    /**
     * 获取跟进记录统计
     * @param $id
     * @param $time
     * @return mixed
     */
    public function getFollowData($id,$num){
        $time = time()-$num*3600*24;
        $result = Follow::getFollowList($id,$time);
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $array['info'] = $result;
        $array['time'] = $times;
        return $array;
    }

    /**
     *获取行为列表
     * @param $uid
     * @param $wu_id
     * @param $size
     * @param $page
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getFollowList($uid,$wu_id,$size=5,$page){
        $result = Follow::getFollow($uid,$wu_id,$size,$page);
        return $result;
    }

    /**
     * 获取一个管理员下的所有成交率
     * @param $t_id
     * @param $type
     * @return array
     */
    public function getAllRateNum($t_id,$type){
        $num = \app\api\model\UserWorkuser::getAllRateNum($t_id,0,$type['0']);
        $num2 = \app\api\model\UserWorkuser::getAllRateNum($t_id,$type['0'],$type['1']);
        $num3 = \app\api\model\UserWorkuser::getAllRateNum($t_id,$type['1'],$type['2']);
        $array = array($num,$num2,$num3);
        return $array;
    }

    /**
     * 获取跟进记录统计
     * @param $id
     * @param $time
     * @return mixed
     */
    public function getAllFollowData($t_id,$num){
        $time = time()-$num*3600*24;
        $result = Follow::getAllFollowList($t_id,$time);
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $array['info'] = $result;
        $array['time'] = $times;
        return $array;
    }

    /**
     * 获取用户数量
     * @param $t_id
     * @param $num
     * @return mixed
     */
    public  function getUserNum($t_id,$num){
        $time = time()-$num*3600*24;
        $result = WorkUser::getUserNum($t_id,$time);
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $array['info'] = $result;
        $array['time'] = $times;
        return $array;
    }

    /**
     * 获取用户排序
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserByCondition($t_id,$type,$num){
        $time = 0;
        $rate = 0;
        if ($type == 'rate' ){
            $rate = $num;
        }else{
            if ($num =='all'){
                $time = time()-time();
            }else{
                $time = time()-$num*3600*24;
            }
        }
        switch ($type)
        {
            case "num":
                $users = WorkUser::getUserByNum($t_id,$time)->toArray();
                $result = array_column($users,'users_count');
                array_multisort($result,SORT_DESC ,$users);
            break;
            case "order":
                $users = WorkUser::getUserByOrder($t_id,$time)->toArray();//订单数量
                $result = array_column($users,'orders_count');
                array_multisort($result,SORT_DESC ,$users);
            break;
            case "interaction":
                $users = WorkUser::getUserByInteraction($t_id,$time)->toArray();//互动量统计
                $users = $this->getCoseRate($users);//互动率计算
                $result = array_column($users,'close_rate');
                array_multisort($result,SORT_DESC ,$users);
                break;
            default:
                $users = [];
        }
        return $users;
    }

    /**
     * yoghurt成交率数量统计
     * @param $t_id
     * @param $begin
     * @param $end
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getUserRateNum($t_id,$begin,$end){
        $users = WorkUser::getUserByRate($t_id,$begin,$end);//成交率
        $result = $users->column('users_count');
        $users = $users->toArray();
        array_multisort($result,SORT_DESC ,$users);
       return $users;
    }

    /**
     * 销售个人参数计算
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserData($wu_id){
        $userData=  WorkUser::getInitiative($wu_id);//互动值
        $userData['initiative'] = $this->getInitiativeRate($userData);//互动值计算
        $userData['active'] = $this->getActiveData($userData);//主动性计算
        $userData['web'] = $this->getWebData($wu_id,$type = 2);//官网推广度
        $userData['goods'] = $this->getWebData($wu_id,$type = 1);//产品推广度
        $userData['prise'] = $this->getWebData($wu_id,$type = 8);//个人魅力值
        $userData['custom'] = $this->getCustomData($wu_id);//获取客户能力值
        return $userData;
    }

    /**
     * @param $users
     * @return mixed
     */
    private function getCoseRate($users)
    {
        foreach ($users as $key => $value) {
            if ($value['touser_count'] != 0 && $value['fromuser_count'] != 0) {
                $rate = sprintf("%.2f",$value['touser_count'] / ($value['fromuser_count'] + $value['touser_count']));
            } else {
                $rate = 0;
            }
            $users[$key]['close_rate'] = $rate;
        }
        return $users;
    }

    /**
     * 互动性数据
     * @param $users
     * @return mixed
     */
    private  function getInitiativeRate($users){
            if ($users['touser_count'] != 0 && $users['fromuser_count'] != 0) {
                $rate = $users['fromuser_count'] / ($users['fromuser_count'] + $users['touser_count']);
                $rate = 20+$rate*80;
            } else {
                $rate = 20;
            }
        return $rate;
    }

    /**
     * 主动型数据
     * @param $users
     * @return mixed
     */
    private function getActiveData($users){
            if ($users['touser_count'] != 0 && $users['fromuser_count'] != 0) {
                $rate = $users['touser_count'] / ($users['fromuser_count'] + $users['touser_count']);
                $rate = 20+$rate*80;
            } else {
                $rate = 20;
            }
        return $rate;
    }
    /**
     * 网页数据
     * @param $users
     * @return mixed
     */
    private function getWebData($wu_id,$type){
        $allNum = WorkUser::getAllBehavior($wu_id)->toArray();//获取总行为数
        $info =  WorkUser::getWebData($wu_id,$type )->toArray();//行为
        if ($allNum['behavior_count'] != 0){
            $rate = 80*$info['behavior_count']/$allNum['behavior_count'] +20;
        }else{
            $rate = 20;
        }

        return $rate;
    }

    /**
     * 能力值计算
     * @param $wu_id
     * @return float|int
     */
    private function getCustomData($wu_id){
        $info =  WorkUser::getUserData($wu_id)->toArray();//获客能力值
        $rate = 80*$info['users_count']/100 +20;
        return $rate;
    }


    /**
     * @param $data
     * @param $rate
     * @param $users
     * @return array
     */
    private function randRate( $rate, $users): array
    {
        $level = 'second_level';
        if ($rate == 0) {
            $level = 'first_level';
        } elseif ($rate == 30) {
            $level = 'second_level';
        } elseif ($rate == 60) {
            $level = 'third_level';
        }
        $result = array_column($users, $level);
        return $result;
    }
}